#pragma once
#include"LogMessage.hpp"
#include<unistd.h>
#include<iostream>
#include<functional>
#include "protocol.hpp"

typedef function<void(int, request&, response&)> fun;
typedef function<void(int, fun)> hand;

void hand_deal(int sockfd, fun _fun)
{
    
    string inbuff;
    while(true)
    {
        //1.接受客户端的消息
        string recv_client, recv_content;
        if (!RecvPackage(sockfd, inbuff, &recv_client)) 
            continue;

        //cout << "这里判断有没有正确收到消息" << recv_client <<endl;
        //2.将客户消息进行反序列化处理并解包协议
        request client_rq;
        response resp_client;

        if (!deLength(recv_client, &recv_content))
        {
            logMessage(ERROR, "deLength client message error");
            break;
        }

        //cout << "这里查看去掉协议，消息是否正常" << recv_content <<endl;

        if (!client_rq.deserializa(recv_content))
        {
            logMessage(ERROR, "deserializa client request error");
            break;
        }

        //cout << "这里查看反序列化后，消息是否正常" << recv_content <<endl;
        //3.将得到的消息进行业务处理
        _fun(sockfd, client_rq, resp_client);

        //4.将处理好的消息进行序列化处理并添加协议内容
        string to_client;
        resp_client.serializa(&to_client);

        to_client = enLength(to_client);

        //5.将序列化后的消息发给客户端
        send(sockfd, to_client.c_str(), to_client.size(), 0);
    }

    close(sockfd);
}



class task{
public:
    task(){}
    task(int fd, const fun& _fun, const hand& _hand)
    :_fd(fd), _callback(_hand), _main_call(_fun) {}

    void operator()()
    {
        _callback(_fd, _main_call);
    }
    
    hand  _callback;
    fun _main_call;
    int _fd;
};